import { useState, useEffect, useMemo } from 'react';
import { Modal, Table, Checkbox, Button, Space, message } from 'antd';
import { useMessage } from '@/hooks/useMessage';
import { findDocOutOfKnowledgeBase, inputDocIntoKnowledgeBase } from '../api';
import { throttle } from '@/utils/debounceThrottle';

const AddExistingDocModal = ({ 
    visible, 
    onCancel, 
    onConfirm,
    knowledgeBaseId,
    title = "从文档中心添加",
    loading = false
}) => {
    const { success, error, contextHolder } = useMessage();
    const [selectedDocs, setSelectedDocs] = useState([]);
    const [tableLoading, setTableLoading] = useState(false);
    const [docList, setDocList] = useState([]);

    // 模拟文档数据 - 实际项目中应该从API获取
    const mockDocList = [
        { id: 1, title: '项目需求规格说明书', owner: '张三', createTime: '2024-01-15' },
        { id: 2, title: '技术实现方案', owner: '李四', createTime: '2024-01-16' },
        { id: 3, title: '周报-2024-07-26', owner: '王五', createTime: '2024-01-17' },
        { id: 4, title: '产品设计文档', owner: '赵六', createTime: '2024-01-18' },
        { id: 5, title: '测试用例文档', owner: '钱七', createTime: '2024-01-19' },
        { id: 6, title: '部署说明文档', owner: '孙八', createTime: '2024-01-20' },
    ];

    // 获取文档列表
    const fetchDocList = async () => {
        setTableLoading(true);
        try {
            if (!knowledgeBaseId) {
                setDocList([]);
                return;
            }
            const res = await findDocOutOfKnowledgeBase({ knowledgeBaseId });
            if (res && res.code === 200 && Array.isArray(res.data)) {
                // 映射为表格需要的字段
                const docs = res.data.map(doc => ({
                    id: doc.docId,
                    title: doc.docName,
                    updateTime: doc.updateTime,
                    createTime: doc.createTime,
                }));
                setDocList(docs);
            } else {
                setDocList([]);
            }
        } catch (err) {
            error({
                content: '获取文档列表失败'
            });
            setDocList([]);
        } finally {
            setTableLoading(false);
        }
    };
    
    // 当弹窗打开时获取文档列表
    useEffect(() => {
        if (visible) {
            fetchDocList();
            setSelectedDocs([]); // 重置选中状态
        }
    }, [visible]);

    // 处理单个文档选择
    const handleDocSelect = (docId, checked, doc) => {
        if (checked) {
            setSelectedDocs(prev => [...prev, docId]);
        } else {
            setSelectedDocs(prev => prev.filter(id => id !== docId));
        }
        navigate(`/knowledgeBase/${knowledgeBaseId}/${doc.id}`);
    };

    // 处理全选
    const handleSelectAll = (checked) => {
        if (checked) {
            setSelectedDocs(docList.map(doc => doc.id));
        } else {
            setSelectedDocs([]);
        }
    };

    // 确认添加
    const [confirmLoading, setConfirmLoading] = useState(false);

    const handleConfirm = async () => {
        setConfirmLoading(true);
        try {
            if (selectedDocs.length === 0) {
                message.error('请至少选择一个文档');
                setConfirmLoading(false);
                return;
            }
            const docIdList = selectedDocs;
            const res = await inputDocIntoKnowledgeBase({
                knowledgeBaseId,
                docIdList
            });
            if (res && res.code === 200) {
                message.success(`成功添加 ${selectedDocs.length} 个文档`);
                if (onConfirm) {
                    onConfirm();
                }
                onCancel();
            } else {
                message.error(res?.msg || '添加文档失败，请重试');
            }
        } catch (err) {
            console.error('添加文档异常', err);
            message.error('添加文档失败，请重试');
        } finally {
            setConfirmLoading(false);
        }
    };

    // 计算全选状态
    const isAllSelected = docList.length > 0 && selectedDocs.length === docList.length;
    const isIndeterminate = selectedDocs.length > 0 && selectedDocs.length < docList.length;

    // 表格列配置
    const columns = [
        {
            title: '文档名称',
            dataIndex: 'title',
            key: 'title',
            width: 120,
            render: (title, record) => (
                <div style={{ cursor: 'pointer' }} onClick={() => handleDocSelect(record.id, !selectedDocs.includes(record.id))}>
                    {title}
                </div>
            ),
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            width: 120,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 120,
        },
    ];

    // 表格行选择配置
    const rowSelection = {
        selectedRowKeys: selectedDocs,
        onChange: (selectedRowKeys) => {
            setSelectedDocs(selectedRowKeys);
        },
        getCheckboxProps: (record) => ({
            name: record.title,
        }),
    };
    const throttledConfirm = useMemo(() => throttle(handleConfirm, 1000), [handleConfirm]);

    return (
        <>
            {contextHolder}
            <Modal
                title={title}
                open={visible}
                onCancel={onCancel}
                footer={[
                    <Button key="cancel" onClick={onCancel}>
                        取消
                    </Button>,
                    <Button 
                        key="confirm" 
                        type="primary" 
                        onClick={throttledConfirm}
                        loading={confirmLoading}
                        disabled={selectedDocs.length === 0}
                    >
                        确定 ({selectedDocs.length})
                    </Button>,
                ]}
                width={800}
                destroyOnClose
            >
                <div style={{ marginBottom: 16 }}>
                    <Space>
                        <Checkbox
                            checked={isAllSelected}
                            indeterminate={isIndeterminate}
                            onChange={(e) => handleSelectAll(e.target.checked)}
                        >
                            全选
                        </Checkbox>
                        <span style={{ color: '#666' }}>
                            已选择 {selectedDocs.length} 个文档
                        </span>
                    </Space>
                </div>
                
                <Table
                    columns={columns}
                    dataSource={docList}
                    rowKey="id"
                    loading={tableLoading}
                    rowSelection={rowSelection}
                    pagination={{
                        pageSize: 10,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
                    }}
                    scroll={{ y: 400 }}
                />
            </Modal>
        </>
    );
};

export default AddExistingDocModal;